﻿using System.Web.Mvc;
using Mvc3Demo.Extentions;

namespace Mvc3Demo.Core
{
    internal class MobileViewEngine : RazorViewEngine
    {
        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            ViewEngineResult result = null;
            var request = controllerContext.HttpContext.Request;
            string deviceType;
            if (HttpExtentions.HasMobileSpecificViews && request.IsSupportedMobileDevice(out deviceType))
            {
                var viewPathAndName = HttpExtentions.ViewsInFolder
                                          ? string.Format("{0}/{1}", deviceType, viewName)
                                          : string.Format("{0}.{1}", deviceType, viewName);

                result = base.FindView(controllerContext, viewPathAndName, masterName, true);

                if (result == null || result.View == null)
                {
                    result = base.FindView(controllerContext, viewPathAndName, masterName, false);
                }
            }
            else
            {
                result = base.FindView(controllerContext, viewName, masterName, useCache);
            }
            return result;
        }

        protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
        {
            return base.FileExists(controllerContext, virtualPath);
        }

        public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            return base.FindPartialView(controllerContext, partialViewName, useCache);
        }
    }
}
